
// TicTacToeAI.java
public class TicTacToeAI extends TicTacToe {
    // Get the best move for the AI
    public int[] getBestMove() {
        int bestScore = Integer.MIN_VALUE;
        int[] bestMove = new int[2];

        for (int row = 0; row < 3; row++) {
            for (int col = 0; col < 3; col++) {
                if (isValidMove(row, col)) {
                    makeMove(row, col);
                    int score = minimax(0, false);
                    makeMove(row, col); // Undo the move

                    if (score > bestScore) {
                        bestScore = score;
                        bestMove[0] = row;
                        bestMove[1] = col;
                    }
                }
            }
        }

        return bestMove;
    }

    // Minimax algorithm
    private int minimax(int depth, boolean isMaximizing) {
        char winner = checkWinner();
        if (winner != ' ') {

            return (winner == currentPlayer) ? 1 : -1;
        }

        if (isDraw()) {
            return 0;
        }

        if (isMaximizing) {
            int bestScore = Integer.MIN_VALUE;
            for (int row = 0; row < 3; row++) {
                for (int col = 0; col < 3; col++) {
                    if (isValidMove(row, col)) {
                        makeMove(row, col);
                        int score = minimax(depth + 1, false);
                        makeMove(row, col); // Undo the move
                        bestScore = Math.max(score, bestScore);
                    }
                }
            }
            return bestScore;
        } else {
            int bestScore = Integer.MAX_VALUE;
            for (int row = 0; row < 3; row++) {
                for (int col = 0; col < 3; col++) {
                    if (isValidMove(row, col)) {
                        makeMove(row, col);
                        int score = minimax(depth + 1, true);
                        makeMove(row, col); // Undo the move
                        bestScore = Math.min(score, bestScore);
                    }
                }
            }
            return bestScore;
        }
    }
}
